package com.zpf.web.servlet;

import cn.dsna.util.images.ValidateCode;
import com.alibaba.druid.util.StringUtils;
import com.zpf.pojo.Address;
import com.zpf.pojo.User;
import com.zpf.service.AddressService;
import com.zpf.service.UserService;
import com.zpf.service.impl.AddressServiceImpl;
import com.zpf.service.impl.UserServiceImpl;
import com.zpf.utils.Base64Utils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * projectName:2022ZPF
 * author:
 * time:2022/4/19 9:43
 * description:
 */
@WebServlet("/userservlet")
public class UserServlet extends BaseServlet {

    UserService userService = new UserServiceImpl();
    AddressService addressService = new AddressServiceImpl();

    public String defaultAddress(HttpServletRequest request,HttpServletResponse response) throws Exception {

        String aid = request.getParameter("id");
        User user = (User) request.getSession().getAttribute("user");

        addressService.setDefaultAddress(aid,user.getId());

        return "redirect:/userservlet?method=getAddress";
    }





    public String updateAddress(HttpServletRequest request,HttpServletResponse response) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");
        int level = Integer.parseInt(request.getParameter("level"));
        int id = Integer.parseInt(request.getParameter("id"));


        if(StringUtils.isEmpty(name)||StringUtils.isEmpty(phone)||StringUtils.isEmpty(detail)){
            System.out.println("数据有误，请重新输入");
            return "redirect:/userservlet?method=getAddress";
        }

        Address address = new Address();
        address.setDetail(detail);
        address.setLevel(level);
        address.setName(name);
        address.setPhone(phone);
        address.setUid(user.getId());
        address.setId(id);

        addressService.update(address);

        return "redirect:/userservlet?method=getAddress";
    }





    public String deleteAddress(HttpServletRequest request,HttpServletResponse response) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        String id = request.getParameter("id");
        addressService.deleteById(id);


        return "redirect:/userservlet?method=getAddress";
    }



    public String addAddress(HttpServletRequest request,HttpServletResponse response) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        String name = request.getParameter("name");
        String phone = request.getParameter("phone");
        String detail = request.getParameter("detail");

        if(StringUtils.isEmpty(name)||StringUtils.isEmpty(phone)||StringUtils.isEmpty(detail)){
            System.out.println("数据有误，请重新输入");
            return "redirect:/userservlet?method=getAddress";
        }

        Address address = new Address();
        address.setDetail(detail);
        address.setLevel(0);
        address.setName(name);
        address.setPhone(phone);
        address.setUid(user.getId());

        addressService.insert(address);

        return "redirect:/userservlet?method=getAddress";
    }

    public String getAddress(HttpServletRequest request,HttpServletResponse response) throws Exception {

        User user = (User) request.getSession().getAttribute("user");
        List<Address> addList = addressService.findAddListByUid(user.getId());

        request.setAttribute("addList",addList);

        return "forward:/self_info.jsp";
    }



    //退出
    /*
    * 1.清楚session
    * 2.清除cookie
    * */
    public String logOut(HttpServletRequest request,HttpServletResponse response) throws Exception{

        //清除session
        request.getSession().removeAttribute("user");
        request.getSession().invalidate();
        //清除cookie
        Cookie cookie=new Cookie("userinfo-2202", Base64Utils.encode(""));
        //生存时间
        cookie.setMaxAge(0);//最大时间
        cookie.setPath("/");//在网站的任意路径可用
        response.addCookie(cookie);

        return  "redirect:/login.jsp";

    }









    //登录
    public String login(HttpServletRequest request,HttpServletResponse response) throws Exception{
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        //判空,跳转页面
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return "redirect:/login.jsp";
        }

            User user= userService.login(username,password);
        if (user != null) {
            //登录成功之后，吧用户信息存储在session中
            request.getSession().setAttribute("user",user);
            //保证点击了按钮
            String auto = request.getParameter("auto");
            if("on".equalsIgnoreCase(auto)){
                String userinfo = username + "#" + password;

                //自动登录，吧登录信息存储到cookie中
                Cookie cookie=new Cookie("userinfo-2202", Base64Utils.encode(userinfo));
                //生存时间
                cookie.setMaxAge(14*24*3600);//最大时间
                cookie.setPath("/");//在网站的任意路径可用
                response.addCookie(cookie);
            }


            return "redirect:/index.jsp";
        }else{
            return "redirect:/login.jsp";
        }

    }
        //验证验证码
    public void checkCode(HttpServletRequest request,HttpServletResponse response) throws Exception{
      //判断输入验证码是否为空
        String code1 = request.getParameter("code");
        if(StringUtils.isEmpty(code1)){
            response.getWriter().print("1");
            return;
        }

        //比较验证码
        String code2 = (String) request.getSession().getAttribute("code");

        if(code1.equalsIgnoreCase(code2)){
            response.getWriter().print("0");
        }else {
            response.getWriter().print("1");
        }

    }

    public void code(HttpServletRequest request,HttpServletResponse response) throws Exception{
        //返回图片
        ValidateCode validateCode = new ValidateCode(120,40,4,20);

        //将验证码存在session中
        request.getSession().setAttribute("code",validateCode.getCode());

        //输出验证码//响应流，输出到前端
        validateCode.write(response.getOutputStream());
    }


















    //注册
    public String register(HttpServletRequest request,HttpServletResponse response){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String gender = request.getParameter("gender");
        //如果数据为空，跳转register.jsp
        if(StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
            return "redirect:/register.jsp";
        }
        //检测用户是否存在
        boolean flag = userService.checkUsername(username);
        if(flag){
            return "redirect:/register.jsp";
        }

        //调用业务层，注册用户，注册成功，跳转登录页面
        boolean isSuccess=userService.register(username,password,email,gender);
        if (isSuccess) {
            return "redirect:/login.jsp";
        }else{
            return "redirect:/register.jsp";
        }
    }
     public void  checkUserName(HttpServletRequest request,HttpServletResponse response) throws Exception{
            //获取username
            String username = request.getParameter("username");
            //判断是否为空
         if(StringUtils.isEmpty(username)){
             response.getWriter().print("2");
         }else{

             //发起校验 （数据库） 如果存在
      boolean flag= userService.checkUsername(username);
             if (flag) {
               response.getWriter().print("1");
             }else{
               response.getWriter().print("0");
             }
         }


    }



}